import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../../../net/api_service.dart';
import '../../../net/httpsClient.dart';
import '../../../services/utils.dart';
import '../models/create_post_entity.dart';

class CategoryController extends GetxController {
  // 表单控制器
  final titleController = TextEditingController();
  final contentController = TextEditingController();

  // 响应式数据
  final isLoading = false.obs;
  final isPublished = true.obs; // true: 发布, false: 草稿

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onClose() {
    titleController.dispose();
    contentController.dispose();
    super.onClose();
  }

  // 创建文章
  Future<void> createPost() async {
    final title = titleController.text.trim();
    final content = contentController.text.trim();

    if (title.isEmpty) {
      SmartDialog.showToast('请输入文章标题');
      return;
    }

    if (content.isEmpty) {
      SmartDialog.showToast('请输入文章内容');
      return;
    }

    isLoading.value = true;
    SmartDialog.showLoading(msg: "发布中...");

    try {
      final request = CreatePostRequest(
        title: title,
        content: content,
        state: isPublished.value ? 1 : 0,
      );

      myLog('创建文章请求: ${request.toJson()}');

      final response = await HttpsClient()
          .post(ApiService.createPost, data: request.toJson());

      if (response == null || response.data == null) {
        SmartDialog.showToast('发布失败，请重试');
        return;
      }

      final entity = CreatePostEntity.fromJson(response.data);
      myLog('创建文章响应: ${response.data}');

      if (entity.code == 100) {
        SmartDialog.showToast(
          isPublished.value ? '文章发布成功！' : '文章保存为草稿！',
          alignment: Alignment.center,
        );

        // 清空表单
        titleController.clear();
        contentController.clear();

        myLog('文章创建成功，ID: ${entity.data}');

        // 可以在这里跳转到文章详情或列表页
        // Get.back(); // 返回上一页
      } else {
        SmartDialog.showToast(
          entity.message ?? '发布失败',
          alignment: Alignment.center,
        );
      }
    } catch (e, stackTrace) {
      myLog('创建文章失败: $e');
      myLog('堆栈跟踪: $stackTrace');
      SmartDialog.showToast('发布失败: $e');
    } finally {
      isLoading.value = false;
      SmartDialog.dismiss();
    }
  }

  // 切换发布状态
  void togglePublishStatus() {
    isPublished.value = !isPublished.value;
  }

  // 清空表单
  void clearForm() {
    titleController.clear();
    contentController.clear();
  }
}
